package com.colorlight.cloud.complete.entity.instructions;

import com.colorlight.cloud.common.exception.ParameterException;
import com.colorlight.cloud.common.model.ExceptionEnum;
import com.colorlight.cloud.complete.api.CompleteEntityScheduleActions;
import com.colorlight.cloud.complete.entity.po.SensorItem;
import com.colorlight.iot.proto.complete.instruction.CompleteInstruction;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.Objects;

/**
 * 获取m2外接亮度传感器数据
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Slf4j
public class GetM2Brightness implements CompleteEntityScheduleActions {

    @Data
    @NoArgsConstructor
    @Builder
    public static class InputMsg implements Serializable {
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class OutputMsg implements Serializable {
        /**
         * 亮度数据，null代表无亮度传感器
         */
        private SensorItem brightnessItem;
    }

    private InputMsg input;
    private OutputMsg output;

    @Override
    public ByteString objectConvertBytes() {
        final CompleteInstruction.GetM2Brightness.InputMsg.Builder inputMsg =
                CompleteInstruction.GetM2Brightness.InputMsg.newBuilder();
        final CompleteInstruction.GetM2Brightness.Builder builder =
                CompleteInstruction.GetM2Brightness.newBuilder();
        builder.setInput(inputMsg);
        return builder.build().toByteString();
    }

    @Override
    public GetM2Brightness byteConvertObject(ByteString bytes) {
        CompleteInstruction.GetM2Brightness getM2Brightness = null;
        try {
            getM2Brightness = CompleteInstruction.GetM2Brightness.parseFrom(bytes);
        } catch (InvalidProtocolBufferException e) {
            log.error("", e);
        }
        if (Objects.isNull(getM2Brightness)) {
            throw new ParameterException(ExceptionEnum.MSG_PARAMETER_EXCEPTION);
        }
        GetM2Brightness.OutputMsg outputMsg = new GetM2Brightness.OutputMsg();
        CompleteInstruction.GetM2Brightness.OutputMsg output = getM2Brightness.getOutput();
        outputMsg.setBrightnessItem(output.hasBrightnessItem() ? new SensorItem().formProto(output.getBrightnessItem()) : null);
        this.setOutput(outputMsg);
        return this;
    }
}

